# -*- coding: utf-8 -*-
import os
import sys
from flask import Flask, request, jsonify
from flask_cors import CORS
from openai import OpenAI
root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 
sys.path.append(root_dir) 
from utils  import api_key_required, call_ali_model, get_db_connection  
from models import init_db, User
import json



 

app = Flask(__name__)
CORS(app)

# 初始化数据库
init_db()

@app.route('/')
def hello_world():
    return 'Hello, World!'

@app.route('/api/chat', methods=['POST'])
@api_key_required
def chat():
    """
    处理聊天消息
    1. 验证API密钥
    2. 保存用户消息
    3. 调用阿里大模型
    4. 返回AI响应
    """
    try:
        app.logger.info('收到聊天请求，开始处理...')
        data = request.get_json()
        if not data:
            app.logger.error('请求体为空或非JSON格式')
            return jsonify({'error': 'Invalid JSON body'}), 400
            
        message = data.get('message')
        #打印 message
        app.logger.info(f'收到消息: {message}')
        if not message:
            app.logger.warning('消息内容为空')
            return jsonify({'error': 'Message is required'}), 400
        
        # 保存用户消息到数据库
        api_key = request.headers.get('X-API-KEY')
        conn = get_db_connection()
        user = conn.execute('SELECT id FROM users WHERE api_key = ?', (api_key,)).fetchone()
        
        if user:
            app.logger.info(f'找到用户ID: {user["id"]}, 开始保存用户消息')
            conn.execute(
                'INSERT INTO chat_messages (user_id, content, sender) VALUES (?, ?, ?)',
                (user['id'], message, 'user')
            )
            conn.commit()
        
        # 调用阿里大模型
        app.logger.info('开始调用阿里大模型API...')
        completion = call_ali_model(message)
    
        # 处理流式响应
        app.logger.info('开始处理流式响应...')
        def generate():
            for chunk in completion:
                if hasattr(chunk, 'model_dump_json'):
                    yield json.dumps(json.loads(chunk.model_dump_json())) 
                else:
                    yield json.dumps(chunk) 
        
        return app.response_class(generate(), mimetype='application/json')
        
    except Exception as e:
        app.logger.error(f'处理聊天请求时发生异常: {str(e)}')
        return jsonify({'error': 'Internal server error'}), 500

@app.route('/api/v1/users', methods=['POST'])
def add_user():
    """
    添加新用户接口
    参数:
        username: 用户名(必填)
        email: 邮箱(必填)
        api_key: API密钥(必填)
    返回:
        成功: 返回用户ID和成功消息
        失败: 返回错误信息
    """
    try:
        data = request.get_json()
        username = data.get('username')
        email = data.get('email')
        api_key = data.get('api_key')
        
        if not all([username, email, api_key]):
            return jsonify({'error': '缺少必填参数'}), 400
            
        user_id = User.insert_user(username, email, api_key)
        return jsonify({
            'user_id': user_id,
            'message': '用户添加成功'
        }), 201
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/verify_key', methods=['POST'])
def verify_key():
    """
    验证API密钥
    """
    api_key = request.headers.get('X-API-KEY')
    if not api_key:
        return jsonify({'valid': False, 'error': 'API key is missing'}), 401
    
    conn = get_db_connection()
    user = conn.execute('SELECT * FROM users WHERE api_key = ?', (api_key,)).fetchone()
    conn.close()
    
    if user is None:
        return jsonify({'valid': False, 'error': 'Invalid API key'}), 401
        
    return jsonify({'valid': True})

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)